﻿using CalligraphyEditor.CalligraphyData;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;

namespace CalligraphyEditor.ViewModel
{
    public static class PhotoHelper
    {

        public static T_Photo BrowserAndUploadPhoto()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Image File|*.jpg;*.jpeg;*.png;*.bmp";
            T_Photo photo = null;
            if (ofd.ShowDialog() == true)
            {
                FileStream fs = new FileStream(ofd.FileName, FileMode.Open);
                photo = PhotoHelper.UploadPhoto(fs);
                fs.Close();
            }
            return photo;
        }

        public static string GetErrorMsg(string[] paths,string[] photoPaths,string[] txtPaths)
        {
            string errorMsg = null;
            int i = 0;
            int[] photoNames1 = new int[photoPaths.Length];
            int[] photoNames2 = new int[photoPaths.Length];
            //检查文件夹中是否有除了‘JPG’，‘BMP’，‘JPEG’，‘PNG’格式外的图片
            foreach (var path in paths)
            {
                string extensionName = GetExtensionName(path);
                if (extensionName == "tiff" || extensionName == "gif" || extensionName == "pcx" ||
                    extensionName == "tga" || extensionName == "exif" || extensionName == "fpx" ||
                    extensionName == "cdr" || extensionName == "psd" || extensionName == "svg" ||
                    extensionName == "pcd" || extensionName == "dxf" || extensionName == "ufo" ||
                    extensionName == "raw" || extensionName == "ai" || extensionName == "eps")
                {

                    errorMsg = "文件内图片格式不正确,请检查文件夹中是否有除了‘JPG’，‘BMP’，‘JPEG’，‘PNG’格式外的图片";
                    goto finish;
                }
            }
            //return errorMsg;

            //检查文件夹中是否有其他格式的文件

            if (paths.Length > (photoPaths.Length + txtPaths.Length))
            {
                errorMsg = "请移除文件夹内除‘JPG’，‘BMP’，‘JPEG’，‘BMP’，‘PNG’格式的图片和‘txt’格式的文本的其他内容";
                goto finish;
            }
            for (i = 0; i < photoPaths.Length; i++)
            {
                int j = 0;
                string nameWithoutExtension = GetFileNameWithoutExtension(GetSafeFileName(photoPaths[i]));
                bool isInt = int.TryParse(nameWithoutExtension, out j);
                if (isInt == false)
                {
                    errorMsg = "图片命名不正确，请用连续的阿拉伯数字命名";
                    goto finish;
                }
                photoNames1[i] = int.Parse(nameWithoutExtension);

            }

            //检查文件夹中的图片是否有缺漏
            var p = from pn in photoNames1 orderby pn select pn;
            photoNames2 = p.ToArray<int>();
            for (i = 0; i < photoNames2.Length; i++)
            {
                if (photoNames2[i] != (i + 1))
                {
                    errorMsg = "文件夹中图片有缺漏或命名错误，请用连续的阿拉伯数字命名";
                    goto finish;
                }
            }

            //检查文件夹中的文本文件命名是否正确
            foreach (var textPath in txtPaths)
            {

                string nameWithoutExtension = GetFileNameWithoutExtension(GetSafeFileName(textPath));
                bool isInt = int.TryParse(nameWithoutExtension, out i);

                if (isInt == false)
                {
                    errorMsg = "文本文件命名不正确，请用与对应的图片名字相同的数字命名";
                    goto finish;
                }
                int name = int.Parse(nameWithoutExtension);
                if (name > photoPaths.Length || name < 1)
                {
                    errorMsg = "文本文件命名不正确，请用与对应的图片名字相同的数字命名";
                    goto finish;
                }
            }
        finish:
            return errorMsg;
        }

        private static string GetFileNameWithoutExtension(string path)
        {
            var safePath = GetSafeFileName(path);
            var strs = safePath.Split('.');
            return strs[0].Trim();
        }

        public static string[] GetPhotoPaths(string[] paths)
        {
            List<string> photoPaths1 = new List<string>();
            int i = 0;
            foreach (var p in paths)
            {
                string extensionName = GetExtensionName(p);
                if (extensionName == "jpg" || extensionName == "jpeg" || extensionName == "bmp" || extensionName == "png")
                {
                    photoPaths1.Add(p);
                }
            }
            string[] photoPaths = new string[photoPaths1.Count];
            foreach (var p in photoPaths1)
            {
                photoPaths[i] = p;
                i++;
            }
            return photoPaths;
        }
        public static string[] GetTxtPaths(string[] paths)
        {
            int i = 0;
            List<string> textPaths1 = new List<string>();
            foreach (var p in paths)
            {
                string extensionName = GetExtensionName(p);
                if (extensionName == "txt")
                {
                    textPaths1.Add(p);
                }
            }
            string[] textPaths = new string[textPaths1.Count()];
            foreach (var t in textPaths1)
            {
                textPaths[i] = t;
            }
            return textPaths;
        }
        public static T_Photo UploadPhoto(string filePath)
        {
            T_Photo photo = new T_Photo ();
            try
            {
                var fs = new FileStream(filePath, FileMode.Open);
                photo = UploadPhoto(fs);
                fs.Close();
                
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message);
            }
            return photo;
        }

        public static T_Photo UploadPhoto(FileStream fileStream )
        {
            EntityDescriptor entity = null;

            T_Photo p = new T_Photo();
            string fileExtension = GetExtensionName(fileStream.Name);

            p.ContentType = "image/" + fileExtension;

            CalligraphyEditor.App.Entities.AddToT_Photo(p);
            BitmapImage imageFromStream = new BitmapImage();
            imageFromStream.BeginInit();
            imageFromStream.StreamSource = fileStream;
            imageFromStream.CacheOption = BitmapCacheOption.OnLoad;
            imageFromStream.EndInit();

            p.Width = imageFromStream.Width;
            p.Height = imageFromStream.Height;
            p.FileSize = fileStream.Length;
            p.Size = "raw";
            

            fileStream.Seek(0, SeekOrigin.Begin);

            string safeFileName = GetSafeFileName(fileStream.Name).Trim();

            CalligraphyEditor.App.Entities.SetSaveStream(p, fileStream, true, p.ContentType, safeFileName);



            try
            {
                var response = CalligraphyEditor.App.Entities.SaveChanges().FirstOrDefault() as ChangeOperationResponse;

                if (p.ID == 0)
                {
                    if (response != null)
                    {
                        entity = response.Descriptor as EntityDescriptor;
                    }

                    // Verify that the entity was created correctly.
                    if (entity != null && entity.EditLink != null)
                    {
                        // Cache the current merge option (we reset to the cached 
                        // value in the finally block).
                        MergeOption mergeOption = CalligraphyEditor.App.Entities.MergeOption;

                        try
                        {
                            // Set the merge option so that server changes win.
                            CalligraphyEditor.App.Entities.MergeOption = MergeOption.OverwriteChanges;

                            // Get the updated entity from the service.
                            // Note: we need Count() just to execute the query.
                            CalligraphyEditor.App.Entities.Execute<T_Photo>(entity.EditLink).Count();
                        }
                        catch (Exception e)
                        {
                            System.Diagnostics.Debug.WriteLine(e.Message);
                        }
                        finally
                        {
                            CalligraphyEditor.App.Entities.MergeOption = mergeOption;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }

            return p;
        }

        private static string GetSafeFileName(string fullPath)
        {
            var strs = fullPath.Split('\\');
            return strs[strs.Length - 1];
            //var nameWithoutExt = name.Split('.')[0];
            //return nameWithoutExt;
        }

        private static string GetExtensionName(string filePath)
        {
            var strs = filePath.Split('.');
            return strs[strs.Length-1].ToLower();
        }

        public static Dictionary<int, string> FilePathsToNums(string[] filePaths)
        {
            Dictionary<int, string> numsFilePaths = new Dictionary<int, string>(filePaths.Length);
            foreach (var fp in filePaths)
            {
                try
                {
                    int num = ParseFilePathToNum(fp);
                    numsFilePaths.Add(num, fp);
                }
                catch (Exception)
                {
                }
            }

            return numsFilePaths;
        }

        private static int ParseFilePathToNum(string filePath)
        {
            var filePaths = filePath.Split('\\');
            var fileName = filePaths[filePaths.Length - 1];
            var fileNames = fileName.Split('.');
            var nameWithoutExt = fileNames[0];
            return int.Parse(nameWithoutExt);
        }

        public static string GetText(int i, Dictionary<int, string> numsTxtFilePaths)
        {
            if (!numsTxtFilePaths.ContainsKey(i))
                return string.Empty;

            string path = numsTxtFilePaths[i];
            if (!System.IO.File.Exists(path))
                return string.Empty;

            var ls = System.IO.File.ReadLines(path);
            var bs = System.IO.File.ReadAllBytes(path);
            return  ASCIIEncoding.GetEncoding("GB2312").GetString(bs);
        }
        public static string GetPath(int i, Dictionary<int, string> photoNumsFilePaths)
        {
            if (!photoNumsFilePaths.ContainsKey(i))
                return string.Empty;

            string path = photoNumsFilePaths[i];
            return path;
        }
    }
}
